package com.jh.concurrent.juc.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title ArrayBlockingQueueDemo.java
 * @package com.jh.concurrent.juc.blockingqueue
 * @description 阻塞队列例子
 * @date 2019-05-24 09:45
 */
public class ArrayBlockingQueueDemo {

    private ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(16);

    {
        init();
    }

    // 模拟消费者一直拉取数据
    public void init() {
        new Thread(() -> {
            while (true){
                try {
                    // take()方法会阻塞主线程，如果获取不到值，主线程会阻塞起来，知道获取到值为止3
                    String obj = queue.take();
                    System.out.println("reseive：" + obj);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // 模拟生产者生产消息
    public void add(String val){
        // add()方法是往阻塞队列中添加元素
        queue.add(val);
        System.out.println("send：" + val);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ArrayBlockingQueueDemo demo = new ArrayBlockingQueueDemo();
        // 模拟生产者一直产生消息
        for (int i = 0; i < 100; i++) {
            demo.add("data" + i);
        }
    }

}
